package com.feng.service.Impl;

import com.feng.dao.UserDao;
import com.feng.dto.Result;
import com.feng.pojo.User;
import com.feng.service.RedisService;
import com.feng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    RedisService redisService;

    @Override
    public Result login(User user, HttpServletResponse response) {
        User userByName = userDao.findByName(user.getUsername());
        if (userByName == null){
            return Result.builder().success(false).massage("不存在用户名").build();
        }
        if (!md5(user.getPassword()).equals(userByName.getPassword())){
            return Result.builder().success(false).massage("密码错误").build();
        }
        String uuid = UUID.randomUUID().toString();
        redisService.set(uuid,userByName,900);
        Cookie cookie = new Cookie("uuid",uuid);
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.builder().success(true).massage("登陆成功").build();
    }

    @Override
    public Result create(User user) {
        User userByName = userDao.findByName(user.getUsername());
        if (userByName != null){
            return Result.builder().success(false).massage("已有同名用户").build();
        }
        user.setPassword(md5(user.getPassword()));
        userDao.create(user);
        return Result.builder().success(true).massage("插入成功").build();
    }

    @Override
    public Result update(User user) {
        userDao.update(user);
        return Result.builder().success(true).massage("成功更新").build();
    }

    @Override
    public Result delete(User user,HttpServletRequest request) {
        userDao.detele(user);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("uuid")){
                String uuid = cookie.getValue();
                redisService.del(uuid);
                break;
            }
        }
        return Result.builder().success(true).massage("成功删除").build();
    }

    private String md5(String password){
        return DigestUtils.md5DigestAsHex((password+"lzf").getBytes());
    }
}
